import { ContextWithMiddleware } from './ContextWithMiddleware';
import type { TypedKey } from './types';

export class PersistentContext extends ContextWithMiddleware {
  constructor(private storageKey: string = 'app-state') {
    super(PersistentContext.loadFromStorage(storageKey));
  }

  private static loadFromStorage(storageKey: string): Record<string, unknown> {
    try {
      if (typeof window === 'undefined') return {};

      const stored = localStorage.getItem(storageKey);
      return stored ? JSON.parse(stored) : {};
    } catch (error) {
      console.warn('Failed to load from localStorage:', error);
      return {};
    }
  }

  setData<T>(key: TypedKey<T>, value: T, immediate = true): void {
    super.setData(key, value, immediate);
    this.saveToStorage();
  }

  private saveToStorage(): void {
    try {
      if (typeof window === 'undefined') return;

      localStorage.setItem(this.storageKey, JSON.stringify(this.data));
    } catch (error) {
      console.warn('Failed to save to localStorage:', error);
    }
  }

  clearStorage(): void {
    try {
      if (typeof window === 'undefined') return;

      localStorage.removeItem(this.storageKey);
      this.data = {};
      this.saveToStorage();
    } catch (error) {
      console.warn('Failed to clear localStorage:', error);
    }
  }
}
